package netDemo

import (
	"fmt"
	"golang.org/x/net/websocket"
	"log"
	"net/http"
)

func echoHandler(ws *websocket.Conn) {
	msg := make([]byte, 512)
	n, err := ws.Read(msg)
	fmt.Println(n, err)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Receive: %s\n", msg[:n])

	send_msg := "[" + string(msg[:n]) + "]"
	m, err := ws.Write([]byte(send_msg))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Send: %s\n", msg[:m])
}

func echoHandlerTest(ws *websocket.Conn) {
	msg := make([]byte, 512)
	n, err := ws.Read(msg)
	fmt.Println(n, err)
	fmt.Println("testRecive: ", msg[:n])

	sendMsg := "[" + string(msg[:n]) + "]"
	m, err := ws.Write([]byte(sendMsg))
	fmt.Println(m, err)
	fmt.Println("testSend: ", m)
}

func main() {
	http.Handle("/echo", websocket.Handler(echoHandler)) // 进行响应
	http.Handle("/", http.FileServer(http.Dir(".")))     // 接到请求

	http.Handle("/testRsp", websocket.Handler(echoHandlerTest)) // 进行响应
	http.Handle("/testReq", http.FileServer(http.Dir(".")))     // 接到请求

	err := http.ListenAndServe(":8081", nil)

	if err != nil {
		panic("ListenAndServe: " + err.Error())
	}
}
